package com.mmall.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.ShippingMapper;
import com.mmall.pojo.Shipping;
import com.mmall.service.IShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("iShippingService")
public class ShippingServiceImpl implements IShippingService {

    @Autowired
    private ShippingMapper shippingMapper;

    public ServerResponse add(Integer userId, Shipping shipping) {
        //传入userId避免其他人地址被恶意更新
        if (userId == null) {
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getMsg());
        }
        if (shipping != null) {
            shipping.setUserId(userId);
            int count = shippingMapper.insert(shipping);
            if (count > 0) {
                return ServerResponse.createBySuccessMessage("新增地址成功");
            }
        }
        return ServerResponse.createByErrorMessage("新增地址失败");
    }

    public ServerResponse delete(Integer userId, Integer shippingId) {
        int count = shippingMapper.deleteByUserIdAndPrimaryKey(userId, shippingId);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("删除地址成功");
        }
        return ServerResponse.createByErrorMessage("删除地址失败");
    }


    public ServerResponse update(Integer userId, Shipping shipping) {
        if (userId == null) {
            return ServerResponse.createByError(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getMsg());
        }
        int count = shippingMapper.updateByPrimaryKeySelective(shipping);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("更新地址成功");
        }
        return ServerResponse.createByErrorMessage("更新地址失败");

    }

    public ServerResponse list(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Shipping> shippings = shippingMapper.selectByUserId(userId);
        PageInfo pageInfo = new PageInfo(shippings);
        return ServerResponse.createBySuccess(pageInfo);
    }


    public ServerResponse select(Integer userId,Integer shippingId){
        Shipping shipping = shippingMapper.selectByUserIdPrimaryKey(userId, shippingId);
        if(shipping==null){
            return ServerResponse.createByErrorMessage("地址不存在");
        }
        return ServerResponse.createBySuccess("地址查询成功",shipping);
    }


}
